import {computed, inject, onBeforeUnmount, provide, reactive} from "@peryl/react-compose";
import {iMicroAppPageButton, iMicroAppPageButtonProcessor} from "@peryl/micro-web";
import {remove} from "@peryl/utils/remove";

/**
 * 页面按钮控制模块
 * @author  韦胜健
 * @date    2024.6.12 22:38
 */
export const MicroAppPageButton = (() => {

  const PROVIDE_NAME = '@@MicroAppPageButton';

  const useProvider = () => {
    const state = reactive({ buttonProcessors: [] as iMicroAppPageButtonProcessor[] });
    const showButtons = computed(() => {
      const buttons: iMicroAppPageButton[] = [];
      state.buttonProcessors.forEach((processor) => {
        const buttonsOrNot = typeof processor === "function" ? processor(buttons) : processor;
        if (buttonsOrNot == null) {return;}
        Array.isArray(buttonsOrNot) ? buttons.push(...buttonsOrNot) : buttons.push(buttonsOrNot);
      });
      return buttons.filter(i => {
        if (i.render) {
          const buttonContent = i.render();
          return buttonContent != null;
        } else {
          return i.show !== false;
        }
      });
    });
    const refer = { state, showButtons };
    provide(PROVIDE_NAME, refer);
    return refer;
  };

  const usePageButton = (buttonProcessor: iMicroAppPageButtonProcessor): boolean => {
    const injection = inject(PROVIDE_NAME, null) as null | ReturnType<typeof useProvider>;
    if (!injection) {return false;}
    injection.state.buttonProcessors.push(buttonProcessor);
    onBeforeUnmount(() => {remove(injection.state.buttonProcessors, buttonProcessor);});
    return true;
  };

  return {
    useProvider,
    usePageButton,
  };
})();

export type iMicroAppPageButtonRefer = ReturnType<typeof MicroAppPageButton.useProvider>

export const usePageButton = MicroAppPageButton.usePageButton;
